<template>
  <view>
    <cover-view class="container">
      <cover-view
        class="content"
        v-for="(item, index) in coupon"
        :key="item.name"
      >
        <cover-view
          @click="change(index)"
          class="item"
          :class="current === index && 'active'"
        >
          {{ item.name }}
        </cover-view>
        <cover-view :class="current === index && 'line'"></cover-view>
      </cover-view>
    </cover-view>

    <Coupon
      :coupon="coupons[current].list"
      v-if="coupons[current].list.length > 0"
    ></Coupon>
  </view>
</template>

<script>
import Coupon from '@/components/coupon'
import { getCodeStatus } from '@/api'
import { coupon } from '@/api/local-data'

Object.freeze(coupon)
export default {
  components: {
    Coupon
  },
  data() {
    return {
      coupon,
      id: '',
      current: 0,
      size: 5,
      page: 1,
      coupons: [
        {
          status: 0,
          list: [],
          page: 1,
          total: ''
        },
        {
          status: 1,
          list: [],
          page: 1,
          total: ''
        },
        {
          status: 2,
          list: [],
          page: 1,
          total: ''
        }
      ]
    }
  },
  created() {
    const { id } = uni.getStorageSync('userInfo')
    this.id = id
    this.getCode()
  },
  onReachBottom() {
    const current = this.coupons[this.current]
    if (current.total != current.list.length) {
      current.page++
      this.getCode()
    }
  },
  methods: {
    getCode() {
      const current = this.coupons[this.current]
      getCodeStatus(this.id, current.status, current.page, this.size).then(
        res => {
          console.log(res)
          current.list = [...current.list, ...res.data.list]
          current.total = res.data.total
        }
      )
    },
    change(index) {
      // 切换tab时清空当前list中的数据，防止数据重叠
      this.current = index
      const current = this.coupons[this.current]
      current.list = []
      current.page = 1
      this.getCode()
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  background: #fff;
  position: fixed;
  top: 0;
  width: 100%;
  display: flex;
  align-items: center;
  height: 90rpx;
  .content {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 90rpx;
    justify-content: center;
    position: relative;
    .active {
      color: #e73835;
    }
    .line {
      position: absolute;
      bottom: 10rpx;
      width: 30%;
      margin-top: 4rpx;
      height: 2px;
      background: #e73835;
    }
  }
}
</style>
